import { FileOutlined } from '@ant-design/icons';
import { ExtendQuestionsInfo, ModifyExtendQuestionRequest } from 'admin/schema/ExtendQuestion';
import {
  batchUnderstandNewWords,
  deleteExtendQuestion,
  getBatchStudyProgress,
  getExtendQuestions,
} from 'admin/servers/servers';
import { Table, Button, ConfigProvider, Divider, message, Modal, Progress } from 'antd';
import Search from 'antd/lib/input/Search';
import { ColumnsType } from 'antd/lib/table';
import { debounce } from 'lodash';

import React, { useCallback, useEffect, useRef, useState } from 'react';
import { clearNull, deleteRowChangePageNum } from 'utils/tools';
import {
  extendTypeOption,
  filterLabelName,
  studyStateOption,
} from '../../../components/RobotsTool';
import ExtendQuestionModel from './components/ExtendQuestionModel';

import NewWordsModel from './components/NewWordsModel';
import './style.scss';

interface Iprops {
  /**意图id、问题id */
  intentionId: number;
  /**组件类型：意图扩展问、问题扩展问 */
  mode: 'intention' | 'question';
  /**更新头部保存按钮状态 */
  fn: Function;
}

/**扩展问题列表（流程配置--意图扩展问、问答扩展问） */
const ExtendQuestion: React.FC<Iprops> = ({ intentionId, mode, fn }) => {
  // 组件类型中文名称
  const modeName = mode === 'intention' ? '意图' : '问题';

  // 搜索条件
  const [searchText, setSearchText] = useState<string>('');
  // 排序
  const [order, setOrder] = useState<'desc' | 'asc' | ''>('');
  // 当前页码
  const [current, setCurrent] = useState<number>(1);
  // 每页条数
  const [pageSize, setPageSize] = useState<number>(10);
  //  数据总数
  const [total, setTotal] = useState<number>(0);
  // Table loading状态
  const [tableLoading, setTableLoading] = useState<boolean>(false);
  // Table数据
  const [tableData, setTableData] = useState<ExtendQuestionsInfo[]>([]);
  // 删除扩展：弹框显示
  const [deleteVisible, setDeleteVisible] = useState<boolean>(false);
  // 删除扩展：扩展ID
  const [deleteExtendQuestionId, setDeleteExtendQuestionId] = useState<number>(0);
  // 删除扩展：确认按钮loading
  const [confirmDeleteLoading, setConfirmDeleteLoading] = useState<boolean>(false);

  // 新建编辑扩展弹窗-显示/隐藏
  const [extendModelVisble, setExtendModelVisble] = useState<boolean>(false);

  // 编辑扩展弹窗-数据
  const [extendModelData, setExtendModelData] = useState<ModifyExtendQuestionRequest | undefined>();

  // 批量学习按钮loading
  const [batchStudyLoading, setBatchStudyLoading] = useState<boolean>(false);
  // 批量学习进度
  const [progressData, setProgressData] = useState(0);

  // 页面卸载标志：true-卸载
  const isUnmount = useRef<any>(undefined);
  // 计时器-刷新列表，显示导入进度计时器
  const timer = useRef<any>(undefined);

  // 新词发现弹窗-props
  const [newWordsModelProp, setNewWordsModelProp] = useState<{
    extendQuestionId: number;
    extendQuestionName: string;
    modeType?: 'study';
  }>();

  /**
   * 查询学习进度
   */
  const checkBatchStudy = useCallback(async () => {
    try {
      const { data } = await getBatchStudyProgress({
        intentionId,
      });
      if (isUnmount.current) {
        console.log('>>>>>>>>>>>页面已经卸载-return >>>>>>>>>>>');
        return;
      }
      console.log('批量学习', data);
      const { isBatchUnderstand, finishedNumber, totalNumber } = data;
      if (isBatchUnderstand) {
        setBatchStudyLoading(true);
        fn(true);
        startTimer();
        // 批量学习中，显示进度条
        const percent = Math.floor(
          (finishedNumber && totalNumber ? finishedNumber / totalNumber : 0) * 100
        );
        console.log(percent);
        setProgressData(percent);
      } else {
        // 非批量学习中
        stopTimer();
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
      quitTimer();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [intentionId]);

  /**
   * Table数据加载
   */
  const initData = useCallback(async () => {
    if (!intentionId) return;
    setTableLoading(true);
    try {
      const param = {
        pageNo: current,
        pageSize: pageSize,
        intentionId,
        extendQuestionName: searchText,
        underStandStatusOrder: order,
      };
      console.log('table--->>>>列表查询数据 param', param);
      const { data, count } = await getExtendQuestions(clearNull(param));
      setTableData(data || []);
      setTotal(Number(count) || 0);
      console.log('table--->>>>列表查询数据 data', data);
      // progressData更新时，表格数据需要更新
      console.log('table--->>>>列表查询数据 progressData', progressData);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setTableLoading(false);
  }, [current, intentionId, order, pageSize, progressData, searchText]);

  // 数据初始化 && 数据更新
  useEffect(() => {
    console.log('come******1');
    isUnmount.current = false;
    checkBatchStudy();
    return () => {
      console.log('leave*******1');
      quitTimer();
      // 卸载中
      isUnmount.current = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [checkBatchStudy]);

  // 数据初始化 && 数据更新
  useEffect(() => {
    initData();
  }, [initData]);

  /**开启定时器 */
  function startTimer() {
    if (timer.current) {
      return;
    }
    // 条件：没有定时器，则开启
    // 开启-定时1s刷新-更新进度条
    timer.current = setInterval(() => {
      console.log('1s****定时刷新-批量学习进度条');
      checkBatchStudy();
    }, 1000);
    console.log('启动定时器', timer.current);
  }

  /**清除定时器:学习完成 */
  function stopTimer() {
    if (!timer.current) {
      return;
    }
    clearInterval(timer.current);
    timer.current = null;

    // 条件：有定时器，说明进度到了100%，则需要清除
    setProgressData(100);
    message.success('批量学习完成');
    setTimeout(() => {
      // 还原页面
      setBatchStudyLoading(false);
      fn(false);
      setProgressData(0);
    }, 300);
  }

  /**清除定时器:出现异常，或者退出页面，需要停止计时器刷新 */
  function quitTimer() {
    if (!timer.current) {
      return;
    }
    clearInterval(timer.current);
    timer.current = null;

    setBatchStudyLoading(false);
    fn(false);
  }
  /**
   * 对table数据进行刷新：新增，编辑
   * @param pageNum 刷新页码
   */
  const refreshTable = async (pageNum?: number) => {
    if (pageNum) {
      current === pageNum ? initData() : setCurrent(pageNum);
    } else {
      initData();
    }
  };

  /**
   * 对table数据进行刷新：删除
   */
  function deleteFresh(size: number) {
    const newPageNum = deleteRowChangePageNum(size, total, current, pageSize);
    refreshTable(newPageNum);
  }
  const columns: ColumnsType<ExtendQuestionsInfo> = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'key',
      width: 80,
      render: (text, record, index) => index + 1 + pageSize * (current - 1),
    },
    {
      title: '扩展问题',
      dataIndex: 'extendQuestionName',
      key: 'extendQuestionName',
    },
    {
      title: '扩展类型',
      dataIndex: 'extendType',
      key: 'extendType',
      width: 200,
      render: text => filterLabelName(extendTypeOption, text),
    },
    {
      title: '匹配严格度',
      dataIndex: 'strictnessLevel',
      key: 'strictnessLevel',
      width: 200,
    },
    {
      title: '学习状态',
      dataIndex: 'underStandStatus',
      key: 'underStandStatus',
      sorter: true,
      // 默认升序
      defaultSortOrder: 'ascend',
      // 禁止排序恢复到默认状态
      sortDirections: ['descend', 'ascend', 'descend'],
      width: 200,
      render: text => filterLabelName(studyStateOption, text),
    },
    {
      title: '操作',
      key: 'operation',
      width: 240,
      render: (text, record, index) => (
        <>
          <Button
            type="link"
            onClick={() => modifyExtendAction(record)}
            disabled={batchStudyLoading}
          >
            编辑
          </Button>
          <Button
            type="link"
            onClick={() => deleteExtendAction(record)}
            disabled={batchStudyLoading}
          >
            删除
          </Button>
          <Button
            key={record.extendQuestionId}
            type="link"
            // onClick={debounce(() => studyNewWordsAction(record), 500)}
            onClick={() => studyNewWordsAction(record)}
            disabled={batchStudyLoading}
          >
            学习
          </Button>
        </>
      ),
    },
  ];
  /**
   * 点击批量学习按钮
   */
  const handleBatchStudy = async () => {
    try {
      await batchUnderstandNewWords({ intentionId });
      setBatchStudyLoading(true);
      fn(true);
      startTimer();
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
      setBatchStudyLoading(false);
      fn(false);
    }
  };

  /**
   * 点击新建扩展按钮
   */
  const extendModelVisbleAction = () => {
    if (!intentionId) {
      // 还没有创建
      message.warning(`请先输入${modeName}名称并保存`);
      return;
    }
    setExtendModelVisble(true);
  };
  /**
   * 编辑扩展操作
   */
  const modifyExtendAction = (record: ExtendQuestionsInfo) => {
    setExtendModelVisble(true);
    setExtendModelData(record);
  };
  /**
   * 操作-学习
   * 逻辑：调发现新词接口，如有新词-弹窗，如无新词-不弹窗
   */
  const studyNewWordsAction = (record: ExtendQuestionsInfo) => {
    console.log('点击-学习>>>新词组件--init', record);
    const { extendQuestionId, extendQuestionName } = record;
    setNewWordsModelProp({ extendQuestionId, extendQuestionName, modeType: 'study' });
  };

  /**
   * 删除扩展操作
   */
  const deleteExtendAction = (record: ExtendQuestionsInfo) => {
    setDeleteExtendQuestionId(record.extendQuestionId);
    setDeleteVisible(true);
  };

  /**
   * 请求删除扩展接口
   * @param extendQuestionId
   */
  const requestDeleteExtend = async (extendQuestionId: number) => {
    setConfirmDeleteLoading(true);
    try {
      const res = await deleteExtendQuestion({
        extendQuestionId,
      });
      if (res.code === 0) {
        message.success('删除扩展成功');
        deleteFresh(1);
      } else {
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
      console.log('deleteExtend -> res', res);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setDeleteVisible(false);
    setConfirmDeleteLoading(false);
  };
  /**
   * 翻页
   * @param pageNo 点击页码
   */
  const onChangeCurrent = (pageNo: number) => {
    setCurrent(pageNo);
  };
  /**
   *改变每页显示条数
   * @param current 当前页码
   * @param pageSize 每页显示条数
   */
  const onChangePageSize = (current: number, pageSize: number) => {
    setPageSize(pageSize);
  };

  /**
   * 搜索
   * @param text 搜索内容
   */
  const handleSearch = (text: string) => {
    if (text !== searchText) {
      setSearchText(text);
      setCurrent(1);
    }
  };
  /**
   * 排序改变
   */
  const onChangeSort = (pagination: any, filters: any, sorter: any) => {
    console.log('排序改变****', sorter);
    const { order } = sorter;
    // 转换为后端接口入参对应字段
    let str: 'desc' | 'asc' | '';
    switch (order) {
      case 'descend':
        str = 'desc';
        break;
      case 'ascend':
        str = 'asc';
        break;
      default:
        str = '';
        break;
    }
    setOrder(str);
  };

  //  分页配置项
  const pagination = {
    total: total,
    showTotal: (total: number) => `共 ${total} 条`,
    current: current,
    pageSize: pageSize,
    showSizeChanger: true,
    onChange: onChangeCurrent,
    onShowSizeChange: onChangePageSize,
  };

  const customizeRenderEmpty = () =>
    //这里面就是我们自己定义的空状态
    !tableLoading && (
      <div style={{ textAlign: 'center' }}>
        <FileOutlined style={{ fontSize: 54, margin: 20 }} />
        <p>
          新建多条{modeName}扩展能帮助系统更准确识别出{modeName}！
        </p>
        <Button
          type="primary"
          style={{ margin: 20 }}
          onClick={extendModelVisbleAction}
          disabled={batchStudyLoading}
        >
          新建扩展
        </Button>
      </div>
    );
  return (
    <>
      <div className="extend-question">
        <div className="mgr-header">
          <div className="mgr-header-left">
            <span className="header-tit">{modeName}扩展</span>
            <Search
              className="mgr-header-search"
              placeholder="请输入扩展问题"
              enterButton="搜索"
              allowClear
              onSearch={value => handleSearch(value.trim())}
            />
          </div>
          <div className="mgr-header-right">
            {batchStudyLoading && (
              <div className="progress-box">
                <span>学习进度</span>
                <Progress percent={progressData} size="small" />
              </div>
            )}
            <Button
              type="primary"
              onClick={debounce(handleBatchStudy, 500)}
              loading={batchStudyLoading}
            >
              批量学习
            </Button>
            <Button type="primary" onClick={extendModelVisbleAction} disabled={batchStudyLoading}>
              新建扩展
            </Button>
          </div>
        </div>
        <Divider style={{ margin: '12px 0' }} />
        <ConfigProvider renderEmpty={customizeRenderEmpty}>
          <Table
            columns={columns}
            loading={tableLoading}
            dataSource={tableData}
            rowKey="extendQuestionId"
            pagination={pagination}
            onChange={onChangeSort}
          />
        </ConfigProvider>
      </div>
      {/* 删除扩展弹框 */}
      <Modal
        title={`删除${modeName}扩展提醒`}
        visible={deleteVisible}
        onOk={() => {
          requestDeleteExtend(deleteExtendQuestionId);
        }}
        confirmLoading={confirmDeleteLoading}
        onCancel={() => {
          setDeleteVisible(false);
        }}
      >
        <p>删除后无法恢复！确定删除吗？</p>
      </Modal>
      {/* 新建、编辑扩展弹框 */}
      <ExtendQuestionModel
        show={extendModelVisble}
        intentionId={intentionId}
        extendProp={extendModelData}
        onClose={() => {
          setExtendModelVisble(false);
          setExtendModelData(undefined);
        }}
        onSuccess={({ extendQuestionId, extendQuestionName }) => {
          // 新建需要重置到第一页；编辑则只需刷新当前页
          extendModelData ? refreshTable() : refreshTable(1);
          setExtendModelVisble(false);
          setExtendModelData(undefined);
          // 继续发现新词逻辑
          setNewWordsModelProp({
            extendQuestionId,
            extendQuestionName,
          });
        }}
      />
      {/* 新词学习-弹窗 */}
      {newWordsModelProp && (
        <NewWordsModel
          modelProp={newWordsModelProp}
          callBack={fresh => {
            console.log('新词组件--close');
            newWordsModelProp && setNewWordsModelProp(undefined);
            // 学习成功
            fresh && refreshTable();
          }}
        />
      )}
    </>
  );
};

export default ExtendQuestion;
